<?php

namespace app\admin\controller\kuerp;

use app\common\controller\Backend;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\Stores;
use app\admin\model\kuerp\StaffMember;
use app\admin\model\kuerp\Goods as GoodsModel;
use think\Db;
use Exception;

/**
 * 商品序列号状态
 *
 * @icon fa fa-circle-o
 */
class GoodsSerialStatus extends Backend
{
    
    /**
     * GoodsSerialLog模型对象
     * @var \app\admin\model\kuerp\GoodsSerialLog
     */
    protected $model = null;
    // protected $childrenSales = [];
    protected $adminids = [];
    protected $storesList = [];

    public function _initialize()
    {
        parent::_initialize();
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);

        $this->model = new \app\admin\model\kuerp\GoodsSerial;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("storeStatusList", $this->model->getStoreStatusList());

        // $serialList = $this->model->getSerialList();
        // $serialLists = [];
        // foreach ($serialList as $serialList_k=>$serialList_v){
        //     $serialLists[] = ['name'=>$serialList_v['serial'],'value'=>$serialList_v['serial']];
        // }
        // $this->view->assign("serialList", $serialList);
        // $this->assignconfig("serialList", $serialLists);
        $adminids = [];
        if (!$this->auth->isSuperAdmin()) {
            //部门经理查看部门成员 上级部门能查看下级部门
            $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
            //转为职员id
            // if ($adminids) {
            //     $this->childrenSales = (new StaffMember())->getStaffMemberIds($adminids);
            // }
        }
        $this->adminids = $adminids;
        $this->storesList = (new Stores())->getStoresList(0, $adminids);
        $this->view->assign("storesList", $this->storesList);
        $this->assignconfig("storesList", $this->storesList);

        $goodsList = (new GoodsModel())->where(['status'=>1, 'serial' => 1])->select();
        $goodsLists = [];
        foreach ($goodsList as $goodsList_k=>$goodsList_v){
            $goodsLists[] = ['name'=>$goodsList_v['goods_name'],'value'=>$goodsList_v['id']];
        }
        $this->view->assign("goodsList", $goodsList);
        $this->assignconfig("goodsList", $goodsLists);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

     /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $store_where = [];
            if (!$this->auth->isSuperAdmin()) {
                $store_where['stores_id'] = ['in',array_column($this->storesList, 'id')];
            }
            
            $list = $this->model
                    ->with(['goods'])
                    ->where($where)
                    ->where($store_where)
                    ->where((new Goods())->setWhere([],'goods_serial'))
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                
                $row->getRelation('goods')->visible(['goods_name']);
            }
            if ($list->items()) {
                $storeList = (new Stores())->getStoresList();
                $storeList = array_column($storeList,'name','id');
                //获取客户
                $sale_codes = array_column($list->items(),'sale_code');
                $customers = Db::name('kuerp_customers')->alias('c')->join('kuerp_goods_sales gs', 'gs.customers_id = c.id', 'left')->where(['gs.purchase_code'=>['in',$sale_codes]])->column('gs.id,customer_name','gs.purchase_code');
                foreach ($list->items() as $list_k=>&$list_v){
                    $list_v['goods_name'] = $list_v['goods']['goods_name'];
                    $list_v['stores_name'] = $storeList[$list_v['stores_id']];
                    $list_v['customer_name'] = $list_v['sale_code'] && !empty($customers[$list_v['sale_code']]) ? $customers[$list_v['sale_code']]['customer_name'] : '';
                    $list_v['goods_salesid'] = $list_v['sale_code'] && !empty($customers[$list_v['sale_code']]) ? $customers[$list_v['sale_code']]['id'] : 0;
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看
     */
    public function indexold()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->where((new Goods())->setWhere())
                    ->field('max(id) as id')
                    ->group('serial')
                    ->paginate($limit);

            foreach ($list as $list_k=>$list_v){
                $info = Db::name('kuerp_goods_serial_log')->where((new Goods())->setWhere(['id'=>$list_v['id']]))->find();
                $list[$list_k]['serial']        = $info['serial'];
                $list[$list_k]['business_type'] = $info['business_type'];
                $list[$list_k]['store_status']  = $info['store_status'];
                $list[$list_k]['purchase_time'] = $info['purchase_time'];
                $list[$list_k]['createtime']    = $info['createtime'];
                $list[$list_k]['purchase_code'] = $info['purchase_code'];
                $list[$list_k]['remarks']       = $info['remarks'];

                $goods = Db::name('kuerp_goods')->where((new Goods())->setWhere(['id'=>$info['goods_id']]))->field('goods_code,goods_name,goods_barcode,goods_specification_id')->find();
                $list[$list_k]['goods_code'] = $goods['goods_code'];
                $list[$list_k]['goods_name'] = $goods['goods_name'];
                $list[$list_k]['goods_spec'] = $goods['goods_specification_id'];

                $stores = Db::name('kuerp_stores')->where((new Goods())->setWhere(['id'=>$info['stores_id']]))->field('store_code,name')->find();
                $list[$list_k]['store_name'] = $stores['name'];
                //供应商/客户
                if($info['business_type']==2 || $info['business_type']==3 || $info['business_type']==7 || $info['business_type']==8){
                    $list[$list_k]['customer_id'] = \think\Db::name('kuerp_suppliers')->where((new Goods())->setWhere(['id'=>$info['customer_id']]))->value('supplyer_name');
                }else if($info['business_type']==4 || $info['business_type']==5 || $info['business_type']==9 || $info['business_type']==10){
                    $list[$list_k]['customer_id'] = \think\Db::name('kuerp_customers')->where((new Goods())->setWhere(['id'=>$info['customer_id']]))->value('customer_name');
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 出库
     *
     * @return void
     */
    public function outbound($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            if (empty($params['sale_id'])) {
                $this->error(__('请选择关联订单'));
            }
            if ($row['store_status'] == 2) {
                $this->error(__('已出库'));
            }
            if ($row['store_status'] == 3 && $row['sale_id'] > 0 && $row['sale_id'] != $params['sale_id']) {
                $this->error(__('该锁号已经待出库，不可重复出库'));
            }
            $goods_sale_info = Db::name('kuerp_goods_sales_info')->where(['id'=>$params['sale_id']])->find();
            if(!$goods_sale_info){
                $this->error(__('关联订单不存在'));
            }
            if ($row['stores_id'] != $goods_sale_info['stores_id']) {
                $this->error(__('该锁号不属于该仓库'));
            }
            $goods_sales = Db::name('kuerp_goods_sales')->where(['purchase_code'=>$goods_sale_info['purchase_code']])->find();
            if(!$goods_sales){
                $this->error(__('关联订单不存在'));
            }
            if ($goods_sales['examine_status'] != 1) {
                $this->error(__('订单未审核通过'));
            } 
            //查询该订单是否有锁号出库
            $count = $this->model->where([
                'sale_code' => $goods_sale_info['purchase_code'],
                'sale_id'   => $goods_sale_info['id'],
                'status' => '3',
                'id' => ['<>', $ids]
            ])->count();
            if ($count == $goods_sale_info['number']) {
                $this->error(__('该订单已全部出库'));
            }

            $goods_log = Db::name('kuerp_goods_log')->where([
                'purchase_code' => $goods_sale_info['purchase_code'],
                'purchase_id'   => $goods_sale_info['id'],
                'purchase_time' => $goods_sale_info['purchase_time'],
                'business_type' => '4',
                'customer_id'   => $goods_sale_info['customers_id'],])->find();

            $result = false;
            Db::startTrans();
            try {
                //更新订单明细 锁号
                $update_info = [];
                $period = $goods_sale_info['period'] ? unserialize($goods_sale_info['period']) : [];
                if (!in_array($row['serial'], array_column($period, 'serial'))){
                    $period[] = [
                        'serial' => $row['serial'],
                        'remark' => $row['remark'],
                    ];
                    $update_info['period'] = serialize($period);
                }
                if ($update_info) {
                    $result =Db::name('kuerp_goods_sales_info')->where(['id'=>$params['sale_id']])->update($update_info);
                    $result =Db::name('kuerp_goods_sales_summary')->where(['salesinfoid'=>$params['sale_id']])->update($update_info);
                }
                //更新订单锁号
                $update_sales = [];
                if (strpos($goods_sales['serials'], $row['serial']) === false) {
                    $update_sales['serials'] = $goods_sales['serials'].','.$row['serial'];
                    $update_sales['lock_code'] = $goods_sales['lock_code'] .','.$row['remark'];
                }
                if ($update_sales) {
                    $result =Db::name('kuerp_goods_sales')->where(['id'=>$goods_sales['id']])->update($update_sales);
                }
                //更新锁号状态信息
                $update_serial = [
                    'status' => 3,
                    'store_status' => 2,
                    'sale_id' => $params['sale_id'],
                    'sale_code' => $goods_sale_info['purchase_code'],
                    'updatetime' => time()
                ];
                $result =Db::name('kuerp_goods_serial')->where(['id'=>$row['id']])->update($update_serial);
                //新增锁号日志
                $serial_log = [
                    'goods_id' => $row['goods_id'],
                    'stores_id' => $row['stores_id'],
                    'attribute_id' => $row['attribute_id'],
                    'serial' => $row['serial'],
                    'business_type'=>'4',
                    'store_status'=>'2',
                    'remarks' => $row['remark'],
                    'purchase_id' => $goods_sale_info['id'],
                    'purchase_code' => $goods_sale_info['purchase_code'],
                    'purchase_time' => $goods_sale_info['purchase_time'],
                    'customer_id' => $goods_sale_info['customers_id'],
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
                $result =Db::name('kuerp_goods_serial_log')->insert($serial_log);
                //更新库存
                $result =Db::name('kuerp_goods')->where(['id'=>$row['goods_id']])->dec('inventory', 1)->update();
                $result =Db::name('kuerp_goods_stock')->where(['goods_id'=>$row['goods_id'], 'stores_id' => $row['stores_id']])->dec('stock', 1)->update();
                //商品收发明细
                if (empty($goods_log)) {
                    $goods_stock_log = (new Goods())->setDataInfo([
                        'purchase_code' => $goods_sale_info['purchase_code'],
                        'purchase_id'   => $goods_sale_info['id'],
                        'purchase_time' => $goods_sale_info['purchase_time'],
                        'business_type' => '4',
                        'customer_id'   => $goods_sale_info['customers_id'],
                        'goods_id'      => $row['id'],
                        'goods_code'    => $row['goods_code'],
                        'attribute_id'  => (float)$row['attribute_id'],
                        'goods_unit'    => (float)$goods_sale_info['goods_unit'],
                        'stores_id'     => (float)$row['stores_id'],
                        'remark'        => $row['remark'],
                        'out_number'    => 1,
                        'out_basics'    => 1,
                        'out_unit'      => 0,
                        'out_cost'      => 0,
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ]);
                    $result = Db::name('kuerp_goods_log')->insert($goods_stock_log);
                }

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error('出库失败');
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
